package com.xiyoo.cw.common.exception;

import com.xiyoo.cw.common.Result;
import com.xiyoo.cw.common.enums.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @Description 全局异常
 * @Author xiyoo
 * @Date 2024/6/18 10:36
 * @Version 1.0
 **/
@Slf4j
@RestControllerAdvice
public class GlobalException {

    /**
     * 方法参数验证异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public String methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        // 从异常对象中拿到ObjectError对象
        ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
        log.error("方法参数验证异常：{}", objectError.getDefaultMessage());
        // 然后提取错误提示信息进行返回
        return objectError.getDefaultMessage();
    }

    /**
     * 系统异常 预期以外异常
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public Result<?> handleUnexpectedServer(Exception ex) {
        log.error("系统异常：{}", ex.toString());
        return new Result<>(ResultCode.ERROR);
    }


    /**
     * Throw异常的拦截
     */
    @ExceptionHandler(Throwable.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public Result<?> exception(Throwable ex) {
        log.error("系统异常：", ex);
        return new Result<>(ResultCode.ERROR);
    }

    /**
     * 自定义的全局异常
     *
     * @param e
     * @return
     */
//    @ExceptionHandler(ApiException.class)
//    public Result<?> apiExceptionHandler(ApiException e) {
//        log.error("自定义异常：{}", e.getMsg());
//        return new Result<>(ResultCode.ERROR.getCode(), e.getMsg());
//    }
}
